package com.cndym.adapterForMobile.global.impl;

import com.cndym.adapterForMobile.IMobileAdapter;
import com.cndym.adapterForMobile.global.BaseGlobalOperator;
import com.cndym.adapterForMobile.tms.bean.MobileOrderBean;
import com.cndym.constant.Constants;
import com.cndym.exception.CndymException;
import com.cndym.exception.ErrCode;
//import com.cndym.producer.ICommonProducer;
import com.cndym.serviceMap.ServiceBean;
import com.cndym.serviceMap.ServiceList;
import com.cndym.utils.JsonBinder;
import com.cndym.utils.SpringUtils;
import com.cndym.utils.TaskUtils;
import com.cndym.utils.Utils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 * Time:2015-05-11 11:22
 */

@Component
public class JsonGlobalOperator extends BaseGlobalOperator {

    private Logger logger = Logger.getLogger(getClass());
    
//    @Resource
//    private ICommonProducer commonProducer;

    @Override
    public String operator(String msg, HttpServletRequest request) {
    	long l1=System.currentTimeMillis();
        Map<String, String> paraMap = null;
        MobileOrderBean orderBean = null;
        Map<String, String> reMap = new HashMap<String, String>();
        
        if (Utils.isNotEmpty(msg)) {
            try {
                paraMap = JsonBinder.buildNormalBinder().getMapper().readValue(msg, new TypeReference<Map<String, String>>() {});
                orderBean = JsonBinder.buildNonDefaultBinder().fromJson(paraMap.get("msg"), MobileOrderBean.class);
            } catch (Exception e) {
                logger.error("", e);
                throw new CndymException(ErrCode.E3002);
            }
            
            
            String cmd = paraMap.get("cmd");
            String sid = paraMap.get("sid");
            String platform = paraMap.get("platform");
            
            try {
	            ServiceBean serviceBean = ServiceList.getServiceBean(cmd.trim());
	            
	            //校验商户
	            checkChannel(cmd, sid);
	 
	        	IMobileAdapter mobileAdapter = (IMobileAdapter) SpringUtils.getBean(serviceBean.getAdapter());
	            paraMap.put("json", msg);
	            //wap需要特殊处理一下,参数接收传递过来的
	            String tmpIp = paraMap.get("ip"), finalIp = "";
	            if (Utils.isNotEmpty(tmpIp) && tmpIp.contains(",")){
	            	finalIp = tmpIp.split(",")[0].trim();
	            }else{
	            	finalIp = tmpIp;
	            }
	            paraMap.put("ip", (Constants.PLATFORM_WAP.equalsIgnoreCase(platform) && Utils.isNotEmpty(finalIp) )? finalIp : Utils.getIpAddress(request));
	            //执行具体业务代码
	            reMap = mobileAdapter.execute(paraMap);
				// 将请求消息与处理结果经JMS发送至任务系统
				TaskUtils.sendMessageToTask(paraMap, reMap, Utils.isNotEmpty(orderBean)?orderBean.getUserCode():null);
            } catch (CndymException e) {
                reMap.put("code", e.getMessage());
                reMap.put("msg", ErrCode.codeToMsg(e.getMessage()));
            } catch (Exception e) {
                logger.error("", e);
                reMap.put("code", ErrCode.E9999);
                reMap.put("msg", ErrCode.codeToMsg(ErrCode.E9999));
            } finally {
            	if (!Utils.isNotEmpty(orderBean)) {
            		orderBean = new MobileOrderBean();
            	}
	            long l2 = System.currentTimeMillis();
	            logger.info("|" + paraMap.get("ip") + "|" + orderBean.getUserCode() + "|" + sid + "|" + platform + "|" + paraMap.get("softVer") + "|" + cmd + "|" + paraMap.get("func") + "|" + reMap.get("code") + "|" + (l2-l1));
            }
        } else {
            reMap.put("code", ErrCode.E3005);
            reMap.put("msg", ErrCode.codeToMsg(ErrCode.E3005));
        }
        return JsonBinder.buildNonDefaultBinder().toJson(reMap);
    }
    
    public void checkChannel(String cmd, String sid){
//    	String cooperationKey = commonProducer.getCooperationKeyBySid(sid);
//        if (Utils.isEmpty(cooperationKey)) {
//			logger.error("cmd:" + cmd + ",sid:" + sid + " ErrCode:2024,msg:" + ErrCode.codeToMsg(ErrCode.E2024));
//			throw new CndymException(ErrCode.E2024);
//        }
    }
}
